package com.probos.bosnatuur.monitor;

import java.util.Date;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class BosNatuurMonitor extends ListActivity {
    private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;

    private static final int ADD_USER = Menu.FIRST;
    
    private static final int EDIT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;

    private ProjectDbAdapter mDbHelper;
    private String mUserName;

    public static final String PREFS_NAME = "BosNatuurPrefs";
    public static final String TAG = "BosNatuurMonitor";
    
    public static final int VIEW_MAP = 0;
    public static final int VIEW_LIST = 1;
    
    private static Context mCtx = null;
    
    static SharedPreferences mSettings; 
    SharedPreferences.Editor mEditor; 

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.project_list);
        
        mCtx = this;
        
        String title = (String) getTitle();
        setTitle(title+": Projecten");
        
        // mDbHelper = new ProjectDbAdapter(this);
        // mDbHelper.open();
        openDatabase();
        
        mDbHelper.LoadHoofdcat();
        mDbHelper.LoadSubcat();
        mDbHelper.LoadFunctie();
        mDbHelper.LoadVisueel();
        mDbHelper.LoadValidatie();
        
        // setTitle("Hallo");
        
        fillData();
        registerForContextMenu(getListView());
        
        Button insertButton = (Button) findViewById(R.id.project_insert);
        insertButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	createProject();
        	}
        });
        
        mSettings = getSharedPreferences(PREFS_NAME, 0); 
        mUserName = mSettings.getString("username", "");
        
        if (mUserName.length() == 0) {
        	getUserName();
        }
        if (mUserName.length() > 0) {
        	Cursor names = mDbHelper.findUser(mUserName);
        	if (names.getCount() == 0) {
        		mDbHelper.createUser(mUserName);
        	}
        	names.close();
        }
    }

//    @Override
//    protected void onPause() {
//    	Log.i(TAG, "Pause");
//    	mDbHelper.close();
//    	super.onPause();
//    }
//    
//    @Override
//    protected void onResume() {
//    	Log.i(TAG, "Resume");
//    	super.onResume();
//    	openDatabase();
//    }
    
    private void openDatabase() {
    	Log.i(TAG, "openDatabase");
    	if (mDbHelper == null) {
        	Log.i(TAG, "new ProjectDbAdapter");
    		mDbHelper = new ProjectDbAdapter(this);
    	}
   		mDbHelper.open();
    }
    
    private void getUserName() {
    	AlertDialog.Builder alert = new AlertDialog.Builder(this);

    	alert.setTitle("Gebruikersnaam");
    	alert.setMessage("Naam:");

    	// Set an EditText view to get user input 
    	final EditText input = new EditText(this);
    	alert.setView(input);

    	alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    	public void onClick(DialogInterface dialog, int whichButton) {
    		mUserName = input.getText().toString();
    		if (mUserName.length() > 0) {
    			mEditor = mSettings.edit();
    			mEditor.putString("username", mUserName); 
    			mEditor.commit();
    		}
    	  }
    	});

    	alert.setNegativeButton("Annuleren", new DialogInterface.OnClickListener() {
    	  public void onClick(DialogInterface dialog, int whichButton) {
    	    // Canceled.
    	  }
    	});

    	alert.show();
    }
    
    private void fillData() {

    	// openDatabase();
    	
        // Get all of the rows from the database and create the item list
    	// Cursor c = mDbHelper.fetchAllProjects();
    	Cursor c = mDbHelper.getProjects();
    	
    	Log.i(TAG, "fillData: " + c.getCount() );
    	
        startManagingCursor(c);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{ProjectDbAdapter.KEY_TITLE, "aantal", "datum"};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.project_name, R.id.project_count, R.id.project_date};
        // int[] to = new int[]{android.R.id.text1};
        
        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter a = new SimpleCursorAdapter(this, R.layout.project_row, c, from, to);
        // SimpleCursorAdapter a = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, from, to);

        a.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
		    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
		    	/*
		        if(columnIndex == 4) {
		        	// column 4 = "Nr"
		        	int kleur = Color.GRAY;
		        	
					SampleView img = (SampleView) view;
					img.setTextColor(Color.WHITE);
					
		        	// index 5 = "hoofd"
					int i = cursor.getColumnIndex("hoofd");
		        	if (!cursor.isNull(i)) {
			        	Integer position = cursor.getInt(i);
			        	
			        	if (position > 0) {
							int colorPos = (position-1) % colors.length;
							
							int clr = colors[colorPos];
							
							int R = clr % 256;
							int G = (clr / 256 ) % 256;
							int B = (clr / 256 / 256 ) % 256;
									  
							kleur = Color.argb(255, R, G, B);

				            img.setSampleColor(kleur);				            
			        	}
			        }
		        	return false;
		        }
	        
		        if(columnIndex == 4) {
		        	// column 4 = "datum"
                    TextView tv = (TextView) view;
                    // int i = cursor.getColumnIndex("datum");
                    // if (cursor.isNull(i)) i = cursor.getColumnIndex("dat_element");

                    String dateStr = cursor.getString(columnIndex);
                    Date d = ProjectDbAdapter.DBStringToDate(dateStr);
                    String ds = ProjectDbAdapter.DateToString(d);
                    // String ts = ProjectDbAdapter.TimeToString(d);
                    
                    if (view.getId()==R.id.project_date) tv.setText(ds);
                    // if (view.getId()==R.id.element_time) tv.setText(ts);
                    
                    ((TextView) view).setText(DateFormat.getDateFormat(mCtx).format(new Date(cursor.getString(columnIndex))));
                    
                    return true; 		        	
		        }
*/		        
                if (view.getId()==R.id.project_date) {
                	String ds = "";
                	if (!cursor.isNull(columnIndex)) {
                		// Date d = new Date(cursor.getString(columnIndex));
                        String dateStr = cursor.getString(columnIndex);
                        Date d = ProjectDbAdapter.DBStringToDate(dateStr);
                        // ds = ProjectDbAdapter.DateToString(d);
                        ds = DateFormat.getMediumDateFormat(mCtx).format(d);                		
                	}
                	((TextView) view).setText(ds);
                	
                	return true; 
                }
                
                if (view.getId()==R.id.project_count) {
                	if (!cursor.isNull(columnIndex)) {
                        int value = cursor.getInt(columnIndex);
                        ((TextView) view).setText("#"+value);
                	}
                	return true; 
                }		        
				return false;		    	
		    }
        });
	        
        setListAdapter(a);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	boolean result = super.onCreateOptionsMenu(menu);
    	menu.add(0, ADD_USER, 0, R.string.add_user);
    	return result;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case ADD_USER:
    		getUserName();
            if (mUserName.length() > 0) {
            	Cursor names = mDbHelper.findUser(mUserName);
            	if (names.getCount() == 0) {
            		mDbHelper.createUser(mUserName);
            	}
            	names.close();
            }   		
    		return true;
    	}
    	return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        
        TextView textView = (TextView) v.findViewById(R.id.project_name); 
        String title = textView.getText().toString(); 
                
        int current_view = mSettings.getInt("current_view", VIEW_LIST);

        Intent i = null;
    	switch (current_view) {
    	case VIEW_LIST:
    		i = new Intent(this, ProjectElements.class);
    		break;
        case VIEW_MAP:
        	i = new Intent(this, ProjectMap.class);
        	break;
    	}
        
    	if (i != null) {
	        i.putExtra(ProjectDbAdapter.KEY_ROWID, id);
	        i.putExtra(ProjectDbAdapter.KEY_TITLE, title);
	        startActivity(i);
    	}
    }
    
    private void createProject() {
        Intent i = new Intent(this, ProjectEdit.class);
        startActivityForResult(i, ACTIVITY_CREATE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        
        if (resultCode == RESULT_OK) {
        	fillData();
        }
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, EDIT_ID, 0, R.string.menu_edit);
        menu.add(0, DELETE_ID, 0, R.string.menu_delete);
     }

    @Override
    public boolean onContextItemSelected(MenuItem item) {    	
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch(item.getItemId()) {
            case DELETE_ID:
                mDbHelper.deleteProject(info.id);
                fillData();
                return true;
            case EDIT_ID:
                Intent i = new Intent(this, ProjectEdit.class);
                i.putExtra(ProjectDbAdapter.KEY_ROWID, info.id);
                startActivityForResult(i, ACTIVITY_EDIT);
                return true;                
        }
        return super.onContextItemSelected(item);
    }
    
    @Override     
    protected void onDestroy() {
        mDbHelper.close();
        super.onDestroy();
    }
}
